﻿var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

var userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        index: true
    },
    password: {
        type: String,
        required: true,
        select: false
    },
    realm: {
        type: String,
        required: true,
        enum: ['teacher', 'student']
    },
    subject: {
        type: String,
        default: "none"
    },
    friends: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}]
});

userSchema.pre('save', function (next) {
    var user = this;
    if (!user.isModified('password')) {
        return next();
    }
    bcrypt.genSalt(function (err, salt) {
        if (err) {
            return next(err);
        }
        bcrypt.hash(user.password, salt, function (err, hash) {
            if (err) {
                return next(err);
            }
            user.password = hash;
            next();
        });
    });
});


userSchema.methods.verifyPassword = function (password, callback) {
    bcrypt.compare(password, this.password, function (err, isMatch) {
        callback(err, isMatch);
    });
};

userSchema.methods.tidyInfo = function () {
    return {username: this.username, _id: this._id, realm: this.realm, subject: this.subject};
};

module.exports = mongoose.model('User', userSchema, 'users');
module.exports.userSchema = userSchema;